package com.qidian.blog.factory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author 郭浩
 * @Date 2022/10/11 16:10
 */
public class MapperFactory {
    private static SqlSessionFactory sqlSessionFactory = null;
    private static Map<Class,Object> map = new HashMap<>();
    // 获取一个mapper
    public static <T> T getMapper(Class<T> clazz){
        T t = null;
        if(map.containsKey(clazz)){
            return clazz.cast(map.get(clazz));
        }
        // 理论上没有就要加载...........
        // 我们直接返回null
        return t;
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

    // 获取一个mapper
    public static <T> T getMapperP(Class<T> clazz){
        return sqlSessionFactory.openSession(true).getMapper(clazz);
    }
    static {
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        try {
            sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsReader("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 读取配置文件，加载所有的mapper
        Properties ps = new Properties();
        InputStream in = MapperFactory.class.getClassLoader().getResourceAsStream("mapper.properties");
        try {
            ps.load(in);
            // 读取所有的属性
            Collection<Object> values = ps.values();
            for (Object obj : values){
                String className = obj.toString();
                try {
                    Class<?> clazz = Class.forName(className);
                    // 获取mapper对象
                    SqlSession sqlSession = sqlSessionFactory.openSession(true);
                    Object mapper = sqlSession.getMapper(clazz);
                    // 将mapper放入map
                    map.put(clazz,mapper);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    throw new RuntimeException("类名:"+className+"有误");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
